<?php

declare(strict_types=1);

namespace App\Amqp\Consumer;

use App\Service\act\LuckyWheelService;
use App\Service\act\TaskService;
use App\Service\BaseService;
use App\Service\UserService;
use Hyperf\Amqp\Result;
use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use Hyperf\Di\Annotation\Inject;
use PhpAmqpLib\Message\AMQPMessage;
use Hyperf\Amqp\Message\Type;
use Psr\Log\LoggerInterface;
use function Hyperf\Support\env;

#[Consumer(exchange: 'task.progress', routingKey: 'task-progress', queue: 'queue-task-progress', name: "TaskProgressConsumer", nums: 2, enable: true)]
class TaskProgressConsumer extends ConsumerMessage
{
    #[Inject]
    protected LoggerInterface $logger;

    protected Type|string $type = Type::DIRECT; // Type::FANOUT

    public function consumeMessage($data, AMQPMessage $message): Result
    {
        try {
            if (!empty($data['act_id']) && $data['act_id'] == env('ACT_LUCKY_WHEEL_ID', 0)) {
                // 处理幸运转盘活动任务进度
                $res = LuckyWheelService::changeUserLuckyWheelTaskProgress(
                    (int)$data['uid'],
                    (int)$data['condition_type'],
                    (int)$data['progress']
                );
            } else { // 处理其他活动任务进度
                $Task = new TaskService();
                // 获取用户信息
                $Task->currUser = UserService::getUserInfo($data['uid']);
                // 处理用户任务进度
                $res = $Task->changeUserTaskProgress(
                    (int)$data['uid'],
                    (int)$data['condition_type'],
                    (int)$data['condition_value'],
                    (int)$data['progress'],
                    $data,
                    $data['is_group']
                );
            }


            if ($res) {
                return Result::ACK;
            } else {
                return Result::REQUEUE;
            }
        } catch (\Throwable $e) {
            $this->logger->alert('TaskProgressConsumer.$data：' . var_export($data, true));
            $this->logger->error('TaskProgressConsumer.Exception：' . $e->getMessage() . $e->getTraceAsString());
            BaseService::setListCache('MQ_PRODUCER_TASK_PROGRESS_EXCEPTION_LIST', json_encode($data));
            return Result::DROP;
        }
    }
}

